package cn.moukou.dictator.controller;

import cn.moukou.dictator.pojo.node.KVNode;
import cn.moukou.dictator.service.node.NodeService;
import cn.moukou.dictator.util.Resp;
import cn.moukou.dictator.vo.NodeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dictator/api/node")
public class KVNodeController {

    @Autowired
    NodeService nodeService;

    @GetMapping("/get/all")
    public Resp<Map<String, Object>> getAllNode() {
        return Resp.ok(nodeService.getAllNodeInMap());
    }

    @GetMapping("/search")
    public Resp<Map<String, Object>> searchNode(@RequestParam("search_word") String word) {
        return Resp.ok(nodeService.getAllNodeInMap());
    }

    @GetMapping("/sys/get/all")
    public Resp<Map<String, Object>> sysGetAllNode(@RequestParam("page") Integer page, @RequestParam("page_size") Integer pageSize) {
        return Resp.ok(nodeService.getAllNodeInPage(page, pageSize));
    }

    @GetMapping("/sys/get/one")
    public Resp<Map<String, Object>> sysGetOneNodeById(@RequestParam("id") Integer id) {
        return Resp.ok(nodeService.getOneNode(id));
    }

    @GetMapping("/get/{type}")
    public Resp<Map<String, Object>> getAllNode(@PathVariable("type") String type, @RequestParam("page") Integer page, @RequestParam("page_size") Integer pageSize) {
        if (page==null) {
            page = 1;
        }
        if(pageSize == null) {
            pageSize = 10;
        }
        return Resp.ok(nodeService.getNodeByType(type, page, pageSize));
    }

    @PostMapping("/sys/add")
    public Resp<NodeVO> addNode(@RequestBody Map<String, Object> params) {
        if(params.get("nodeType")==null) {
            return Resp.fail("nodeType不可为空");
        }
        NodeVO ret = nodeService.addNode(params);
        if(ret!=null) {
            return Resp.ok(ret);
        } else {
            return Resp.fail(null);
        }
    }

    @PostMapping("/sys/delete")
    Resp<String> deleteNodeById(@RequestParam("id") Integer id) {
        nodeService.deleteNode(new Long(id));
        return Resp.ok("删除成功");
    }

    @PostMapping("/sys/update")
    Resp<String> updateNodeById(@RequestBody Map<String, Object> params) {
        boolean success = nodeService.updateNode(params);
        if (success) {
            return Resp.ok("修改成功");
        } else {
            return Resp.fail("修改失败");
        }
    }
}
